<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="50%"
    @close="cancel"
    :close-on-click-modal="false"
  >
    <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="上级部门" prop="parentId" style="position: relative">
        <el-tree-select
          v-model="form.parentId"
          :data="deptOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="选择上级部门"
          check-strictly
          :render-after-expand="false"
          style="width: 100%"
        />

      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="场所类型" prop="belong">
        <el-select v-model="form.belong" placeholder="请选择场所类型">
          <el-option :value="1" label="酒店"></el-option>
          <el-option :value="2" label="单位"></el-option>
          <el-option :value="3" label="学校"></el-option>
          <el-option :value="4" label="商场"></el-option>
          <el-option :value="5" label="医院"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="省/市/区"  prop="region"
                    :rules="{
        required: true,
        validator: validateRegion,
        trigger: 'change'
      }">
        <region-selector
            ref="regionSelectorRef"
            v-model="form.region"
            @change="handleRegionChange"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="textArea">
        <el-input :rows="2" placeholder="请输入内容" v-model="form.textArea">
        </el-input>
      </el-form-item>

      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
      </el-form-item>
      <el-form-item label="负责人" prop="leader" v-if="false">
        <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone" v-if="false">
        <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" v-if="false">
        <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">正常</el-radio>
          <el-radio :value="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { listDept, getDept, addDept, updateDept } from '@/api/dept'
import RegionSelector from '@/components/RegionSelector'

interface DeptForm {
  id?: number
  parentId: number | null
  name: string
  sort: number
  status: 0 | 1
  textArea: string
  belong: number | null
  region: {
    province: string
    city: string
    area: string
  }
}

const emit = defineEmits(['success'])

// 表单ref
const deptFormRef = ref<FormInstance>()
// 显示状态
const dialogVisible = ref(false)
// 标题
const title = ref('新增部门')
// 部门树选项
const deptOptions = ref([])
// 提交状态
const submitLoading = ref(false)

// 表单数据
const form = reactive<DeptForm>({
  parentId: null,
  name: '',
  sort: 0,
  status: 1,
  textArea: '',
  belong: null,
  region: {
    province: '',
    city: '',
    area: ''
  }
})
// 地区选择变化事件
const handleRegionChange = (region) => {
  console.log('选择的地区:', region)
}
// 地区选择器的自定义校验方法
const validateRegion = (rule, value, callback) => {
  if (!value.province) {
    callback(new Error('请选择省份'))
    return
  }
  if (!value.city) {
    callback(new Error('请选择城市'))
    return
  }
  if (!value.area) {
    callback(new Error('请选择区/县'))
    return
  }
  callback()
}
// 表单校验规则
const rules = reactive({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择上级部门', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ],
  belong: [
    { required: true, message: '请选择场所类型', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})
/** 表单校验 - 检查上级部门选择 */
const validateParentId = (formData: DeptForm) => {
  console.log(formData);
  // 当前是编辑状态且选择了自己作为上级部门
  if (formData.id && formData.id === formData.parentId) {
    return '不能选择自己作为上级部门'
  }
  return ''
}

/** 获取部门树选项 */
const getDeptTree = async () => {
  try {
    const res = await listDept()
    const root = { id: 1, name: '北京东圣', children: [] }
    root.children = res.data
    deptOptions.value = [root]
  } catch (error: any) {
    console.error('获取部门树失败:', error)
  }
}

/** 表单重置 */
const reset = () => {
  form.id = undefined
  form.parentId = null
  form.name = ''
  form.sort = 0
  form.status = 1
  form.textArea = '',
  form.belong = null,
  form.region = {
    province: '',
    city: '',
    area: ''
  }
  deptFormRef.value?.resetFields()
}

/** 取消按钮 */
const cancel = () => {
  reset()
  dialogVisible.value = false
}

/** 新增/修改操作 */
const submitForm = async () => {
  if (!deptFormRef.value) return
  // 先进行上级部门选择的校验
  const errorMsg = validateParentId(form)
  if (errorMsg) {
    ElMessage.error(errorMsg)
    return
  }
  await deptFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true

      // 构造提交数据
      const submitData = {
        id: form.id,
        parentId: form.parentId,
        name: form.name,
        sort: form.sort,
        status: form.status,
        belong: form.belong,
        tcProvince: form.region.province,
        tcCity: form.region.city,
        tcArea: form.region.area,
        textArea: form.textArea
      }

      try {
        if (form.id) {
          // 修改
          await updateDept(submitData)
          ElMessage.success('修改成功')
        } else {
          await addDept(submitData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error: any) {
        ElMessage.error(error.msg || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/** 显示弹框 */
const show = async (row?: Partial<DeptForm>) => {
  reset()
  await getDeptTree()

  if (row?.id) {
    const res = await getDept(row.id)
    Object.assign(form, res.data)

    form.region = {
      province: res.data.tcProvince || '',
      city: res.data.tcCity || '',
      area: res.data.tcArea || '',
    }
    form.belong = res.data.belong || null
    title.value = '修改部门'
  } else {
    title.value = '新增部门'
    form.parentId = null
    form.name = ''
    form.sort = 0
    form.status = 1
    form.textArea = '',
        form.belong = null,
    form.region = {
      province: '',
      city: '',
      area: ''
    }
    if (row) {
      form.parentId = row.id!
    }
  }

  dialogVisible.value = true
}

defineExpose({
  show
})
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
}
</style>